#include "usart.h"
#include "esp8266.h"
#include <string.h>
#include <stdio.h>
#include <stdlib.h>

#define ESP8266_WIFI_INFO "AT+CWJAP=\"Magic7\",\"11111111\"\r\n"

//UART_HandleTypeDef huart3;
volatile uint8_t esp8266_buf[128];
volatile uint16_t esp8266_cnt = 0, esp8266_cntPre = 0;
volatile uint8_t data_bytes;
uint8_t rx_char;

// 清空接收缓冲区
void ESP8266_Clear(void) {
    memset((void*)esp8266_buf, 0, sizeof(esp8266_buf));
    esp8266_cnt = 0;
}

// 等待接收完成
_Bool ESP8266_WaitRecive(void) {
    if (esp8266_cnt == 0)
        return REV_WAIT;

    if (esp8266_cnt == esp8266_cntPre) {
        esp8266_cnt = 0;
        return REV_OK;
    }

    esp8266_cntPre = esp8266_cnt;
    return REV_WAIT;
}

// 发送AT指令
_Bool ESP8266_SendCmd(char *cmd, char *res) {
    uint16_t timeOut = 200;

    HAL_UART_Transmit(&huart3, (uint8_t*)cmd, strlen(cmd), HAL_MAX_DELAY);

    while (timeOut--) {
        if (ESP8266_WaitRecive() == REV_OK) {
            if (strstr((const char*)esp8266_buf, res) != NULL) {
                ESP8266_Clear();
                return 0;
            }
        }
        HAL_Delay(10);
    }
    return 1;
}

// 发送数据
void ESP8266_SendData(uint8_t *data, uint16_t len) {
    char cmdBuf[32];
    ESP8266_Clear();
    sprintf(cmdBuf, "AT+CIPSEND=%d\r\n", len);
    if (!ESP8266_SendCmd(cmdBuf, ">")) {
        HAL_UART_Transmit(&huart3, data, len, HAL_MAX_DELAY);
    }
}

// 获取IPD数据
uint8_t* ESP8266_GetIPD(uint16_t timeOut) {
    char *ptrIPD = NULL;
    char bytes[4] = {0};
    uint8_t i = 0;

    do {
        if (ESP8266_WaitRecive() == REV_OK) {
            ptrIPD = strstr((char*)esp8266_buf, "IPD,");
            if (ptrIPD != NULL) {
                ptrIPD = strchr(ptrIPD, ',');
                while (*ptrIPD < '0' || *ptrIPD > '9') {
                    if (*ptrIPD == '\0') return NULL;
                    ptrIPD++;
                }
                while (*ptrIPD >= '0' && *ptrIPD <= '9')
                    bytes[i++] = *ptrIPD++;
                data_bytes = atoi(bytes);
                
                while (*ptrIPD != ':' && *ptrIPD != '\0') ptrIPD++;
                if (*ptrIPD != '\0') {
                    ptrIPD++;
                    return (uint8_t*)ptrIPD;
                }
            }
        }
        HAL_Delay(5);
    } while (timeOut--);

    return NULL;
}

//// USART3初始化
//void MX_USART3_UART_Init(void) {
//    huart3.Instance = USART3;
//    huart3.Init.BaudRate = 115200;
//    huart3.Init.WordLength = UART_WORDLENGTH_8B;
//    huart3.Init.StopBits = UART_STOPBITS_1;
//    huart3.Init.Parity = UART_PARITY_NONE;
//    huart3.Init.Mode = UART_MODE_TX_RX;
//    huart3.Init.HwFlowCtl = UART_HWCONTROL_NONE;
//    huart3.Init.OverSampling = UART_OVERSAMPLING_16;
//    HAL_UART_Init(&huart3);
//}

// HAL库回调函数
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart) {
    if (huart->Instance == USART3) {
        if (esp8266_cnt < sizeof(esp8266_buf)) {
            esp8266_buf[esp8266_cnt++] = rx_char;
        }
        HAL_UART_Receive_IT(&huart3, &rx_char, 1);
    }
}

// 初始化ESP8266模块
void ESP8266_Init(void) {
//    GPIO_InitTypeDef GPIO_InitStruct = {0};

//    // 复位引脚配置（示例使用PC14）
//    __HAL_RCC_GPIOC_CLK_ENABLE();
//    GPIO_InitStruct.Pin = GPIO_PIN_14;
//    GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
//    GPIO_InitStruct.Pull = GPIO_NOPULL;
//    GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH;
//    HAL_GPIO_Init(GPIOC, &GPIO_InitStruct);

//    // 复位操作
//    HAL_GPIO_WritePin(GPIOC, GPIO_PIN_14, GPIO_PIN_RESET);
//    HAL_Delay(250);
//    HAL_GPIO_WritePin(GPIOC, GPIO_PIN_14, GPIO_PIN_SET);
//    HAL_Delay(500);

    //MX_USART3_UART_Init();
    HAL_UART_Receive_IT(&huart3, &rx_char, 1); // 启动接收中断

    while (ESP8266_SendCmd("AT\r\n", "OK")) HAL_Delay(500);
    while (ESP8266_SendCmd("AT+CWMODE=1\r\n", "OK")) HAL_Delay(500);
    while (ESP8266_SendCmd("AT+CWDHCP=1,1\r\n", "OK")) HAL_Delay(500);
    while (ESP8266_SendCmd(ESP8266_WIFI_INFO, "GOT IP")) HAL_Delay(500);
}

// USART3中断服务函数
//void USART3_IRQHandler(void) {
//    HAL_UART_IRQHandler(&huart3);
//}